package com.sc.nft.dao;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sc.nft.entity.UserAccountFlow;
import com.sc.nft.enums.PayChannelEnum;
import com.sc.nft.mapper.ScUserAccountFlowMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;


@Slf4j
@Repository
public class UserOrderAccountFlowDao extends ServiceImpl<ScUserAccountFlowMapper, UserAccountFlow> {

    /**
     * 查询或初始化钱包
     *
     * @param userId
     * @param payChannelEnum
     * @return
     */
    public UserAccountFlow queryOrInit(Long userId, PayChannelEnum payChannelEnum) {
        UserAccountFlow flow = this.getFlowByUserAndPayChannel(userId, payChannelEnum);
        if (ObjectUtil.isNull(flow)) {
            flow = new UserAccountFlow();
            flow.setUserId(userId);
            flow.setPayChannel(payChannelEnum);
            flow.setFreezeAmount(BigDecimal.ZERO);
            flow.setTotalAmount(BigDecimal.ZERO);
            flow.setUnsettleAmount(BigDecimal.ZERO);
            flow.setSettledAmount(BigDecimal.ZERO);
            flow = this.saveFlow(flow);
        }
        return flow;
    }


    /**
     * 保存用户渠道结算明细
     *
     * @param userAccountFlow
     * @return
     */
    public UserAccountFlow saveFlow(UserAccountFlow userAccountFlow) {
        this.save(userAccountFlow);
        return userAccountFlow;
    }


    /**
     * 查询用户渠道结算明细
     *
     * @param userId
     * @param payChannelEnum
     * @return
     */
    public UserAccountFlow getFlowByUserAndPayChannel(Long userId, PayChannelEnum payChannelEnum) {
        LambdaQueryWrapper<UserAccountFlow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAccountFlow::getUserId, userId);
        queryWrapper.eq(UserAccountFlow::getPayChannel, payChannelEnum);
        return getOne(queryWrapper);
    }


    /**
     * 增加金额 防空初始化
     *
     * @param userId
     * @param payChannelEnum
     * @param amount
     * @return
     */
    public Integer increase(Long userId, PayChannelEnum payChannelEnum, BigDecimal amount) {
        UserAccountFlow userAccountFlow = this.queryOrInit(userId, payChannelEnum);
        return this.baseMapper.increase(userAccountFlow.getId(), amount);
    }

    /**
     * 分账 防空初始化
     *
     * @param userId
     * @param payChannelEnum
     * @param amount
     * @return
     */
    public Integer settle(Long userId, PayChannelEnum payChannelEnum, BigDecimal amount) {
        UserAccountFlow userAccountFlow = this.queryOrInit(userId, payChannelEnum);
        return this.baseMapper.settle(userAccountFlow.getId(), amount);
    }



}
